﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace Ws.Client
{
    /// <summary>
    /// 用于请求Fsu Webservice，使用 HttpClient来完成，封装了外层的soap协议
    /// <br>
    /// 1. 正常来讲，组装的请求参数，外面要包一层Soap协议，而soap各层，需要自定义的参数，但目前用写好的内容构建，如果后续更改了namespace，action， method，param的内容，再扩展封装
    /// </summary>
    public class WsClient
    {
        // 接口地址url
        private string Url = string.Empty;
        // 请求参数
        private string Param = string.Empty;

        //// namespace命名空间
        //private string ns = "http://FSUService.chinamobile.com";
        //// 请求方法名
        //private string funName = string.Empty;


        public WsClient()
        {
            throw new NotImplementedException();
        }

        public WsClient(string url)
        {
            Url = url;
        }


        /// <summary>
        /// 请求接口
        /// <p>1 验证Url 和 参数</p>
        /// <p>2 解析调外层Soap包裹</p>
        /// </summary>
        /// <param name="param">B接口要求格式的入参报文</param>
        /// <returns>B接口要求格式的返回结果报文</returns>
        public async Task<string> Request(string param)
        {
            if (string.IsNullOrEmpty(Url))
            {
                string res = "接口地址为空！";
                Console.WriteLine(res);
                return res;
            }

            if (!Url.Contains("http"))
            {
                string res = "非法接口地址！";
                Console.WriteLine(res);
                return res;
            }

            if (string.IsNullOrEmpty(param))
            {
                string res = "请求参数为空！";
                Console.WriteLine(res);
                return res;
            }

            Param = param;

            HttpClient httpClient = new(); // HttpClient本身已经做了很精细的封装，如果没有更优质的封装，直接New就行
            try
            {
                // soap参数
                string payload =
                    @"<?xml version=""1.0""?>  
                        <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">  
                            <soap:Body>  
                            <invoke xmlns=""http://FSUService.chinamobile.com"">  
                                <xmlData>" + Param +
                           @"</xmlData>  
                            </invoke>  
                            </soap:Body>  
                        </soap:Envelope>";

                // 发送 SOAP 请求并获取响应  
                HttpResponseMessage response = await httpClient.PostAsync(Url, new StringContent(payload, Encoding.UTF8, "text/xml"));

                // 解析 SOAP 响应  
                string respStr = await response.Content.ReadAsStringAsync();
                httpClient = null; // 告诉内存可以清掉了

                string pattern = "<invokeReturn>(.*?)</invokeReturn>";
                Regex regex = new Regex(pattern);
                Match match = regex.Match(respStr);

                if (match.Success)
                {
                    respStr = match.Groups[1].Value;
                    respStr = HttpUtility.HtmlDecode(respStr);
                }
                else
                {
                    string res = "返回结果解析失败 -> 返回结果里的结点和预期不同。";
                    Console.WriteLine(res);
                }
                return respStr;

            }
            catch (HttpRequestException e)
            {
                string res = "WsClient -> Request()异常";
                Console.WriteLine(res);
            }
            finally
            {
                // 将 httpClient 设置为 null，以便垃圾回收器能够释放资源  
                httpClient = null;
            }

            return "";
        }


    }
}
